package com.czy.daishusys.ui.order;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.czy.daishusys.R;
import com.czy.daishusys.adapter.HomeOrderItemAdapter;
import com.czy.daishusys.db.UserHelper;
import com.czy.daishusys.entity.HomeOrderModel;
import com.czy.daishusys.entity.OrderDetailModel;
import com.czy.daishusys.global.Constants;
import com.czy.daishusys.ui.BaseActivity;
import com.czy.daishusys.utils.GsonUtils;
import com.czy.daishusys.utils.JsonUtil;
import com.czy.daishusys.utils.PhoneUtils;
import com.czy.daishusys.utils.StatusBarUtil;
import com.czy.daishusys.widget.MyRecyclerView;
import com.czy.daishusys.widget.RoundImageView;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.HttpParams;

import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.text.SimpleDateFormat;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class OrderDetailActivity extends BaseActivity {
    //发货跳转TYPE
    private static final int DETAIL_DELIVER_TYPE=0x11;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.tv_consignee_name)
    TextView tvConsigneeName;
    @BindView(R.id.tv_consignee_phone)
    TextView tvConsigneePhone;
    @BindView(R.id.tv_consignee_address)
    TextView tvConsigneeAddress;
    @BindView(R.id.iv_customer_img)
    RoundImageView ivCustomerImg;
    @BindView(R.id.tv_customer_name)
    TextView tvCustomerName;
    @BindView(R.id.tv_order_time)
    TextView tvOrderTime;
    @BindView(R.id.rv_order_detail_goods)
    MyRecyclerView rvOrderDetailGoods;
    @BindView(R.id.tv_order_freight)
    TextView tvOrderFreight;
    @BindView(R.id.tv_order_service)
    TextView tvOrderService;
    @BindView(R.id.tv_order_denomination)
    TextView tvOrderDenomination;
    @BindView(R.id.tv_actual_pay)
    TextView tvActualPay;
    @BindView(R.id.tv_order_num)
    TextView tvOrderNum;


    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_order_detail;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        StatusBarUtil.setColor(this, getResources().getColor(R.color.orderToolbarColor));
        toolbarTitle.setText(R.string.order_detail);
        toolbar.setBackgroundColor(getResources().getColor(R.color.orderToolbarColor));
        getOrderInfo();
    }


    @Override
    protected void updateViews() {

    }

    private void getOrderInfo() {
        mMProgressDialog.show();
        HttpParams params = new HttpParams();
        params.put("session", UserHelper.getInstance().getSessionInfoModel(this).getSession());
        params.put("orderId", getIntent().getIntExtra("orderId", 0) + "");
        params.put("pid",UserHelper.getInstance().getDevicePid());
        EasyHttp.post(Constants.SYS_ORDER_DETAIL).params(params).execute(new SimpleCallBack<String>() {
            @Override
            public void onError(ApiException e) {
                PhoneUtils.ShowToastMessage(OrderDetailActivity.this, e.getMessage());
            }


            @Override
            public void onCompleted() {
                super.onCompleted();
                mMProgressDialog.dismiss();
            }

            @Override
            public void onSuccess(String result) {
                String exp = JsonUtil.getJsonValuesString(result, "exp");
                boolean flag = JsonUtil.getJsonValuesBoolean(result, "flag");
                if (flag) {
                    OrderDetailModel.DataBean model = GsonUtils.fromJson(result, OrderDetailModel.class).getData();
                    setOrderData(model);
                }
                else {
                    PhoneUtils.ShowToastMessage(OrderDetailActivity.this, exp);
                }

            }
        });


    }

    private void setOrderData(OrderDetailModel.DataBean model) {
        switch (model.getOrderStatus()) {
            //：待付款，waitDelivery：待发货，delivery：已发货，toInstall：待安装，completed：已完成，commented：已评价，cancelled：已取消,多个状态以逗号分割
            case "waitDelivery":
                break;
            default:
                PhoneUtils.ShowToastMessage(OrderDetailActivity.this, "订单状态发生改变，请刷新列表后重试!");
                finish();
                break;
        }
        tvOrderNum.setText("订单编号: " + model.getOrderNumber());

        tvConsigneeName.setText("收货人: " + model.getShippingAddressName());
        tvConsigneePhone.setText(model.getShippingAddressContact());
        tvConsigneeAddress.setText("收货地址: " + model.getShippingAddress());
        x.image().bind(ivCustomerImg, model.getUserLogo(), new ImageOptions.Builder()
                .setIgnoreGif(false)
                .setFailureDrawableId(R.mipmap.icon_order_member_default)
                .setLoadingDrawableId(R.mipmap.icon_order_member_default)
                .build());
        tvCustomerName.setText(model.getNickName());
        tvOrderTime.setText(formatTime(model.getPayTime()));
        HomeOrderItemAdapter adapter = new HomeOrderItemAdapter(R.layout.item_home_order_item_recycler, model.getOrderItems());
        rvOrderDetailGoods.setAdapter(adapter);
        rvOrderDetailGoods.setLayoutManager(new LinearLayoutManager(this));
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                HomeOrderModel.DataBean.ListBean.OrderItemsBean model = (HomeOrderModel.DataBean.ListBean.OrderItemsBean)adapter.getData().get(position);
                Intent intent = new Intent(OrderDetailActivity.this,GoodsDetailActivity.class);
                intent.putExtra("specGroupKey",model.getSpecGroupKey());
                startActivity(intent);
            }
        });
        tvOrderFreight.setText("¥" + String.format("%.2f", model.getFreight()));
        double price = 0.0;
        double denomination = 0.0;
        for (int i = 0; i < model.getOrderItems().size(); i++) {
            if (model.getOrderItems().get(i).getNeedService()) {
                price += model.getOrderItems().get(i).getServicePrice();
            }
            denomination += model.getOrderItems().get(i).getDiscountPrice();
        }
        tvOrderService.setText("¥" + String.format("%.2f", price));
        tvOrderDenomination.setText("¥" + String.format("%.2f", denomination));
        double actualPay = (price + model.getTotal() + model.getFreight() - denomination) >= 0 ? (price + model.getTotal() + model.getFreight() - denomination) : 0;
        tvActualPay.setText("¥" + String.format("%.2f", actualPay));

    }

    public static String formatTime(long timeStamp) {
        if (timeStamp > 0) {
            String formatDate = "yyyy-MM-dd HH:mm:ss";
            SimpleDateFormat dateFormat = new SimpleDateFormat(formatDate);
            String tmpDateStr = dateFormat.format(timeStamp);
            return tmpDateStr;
        }
        return "";

    }


    @OnClick(R.id.tv_order_detail_deliver)
    public void onViewClicked() {
        Intent intent = new Intent(this, DeliverGoodsActivity.class);
        intent.putExtra("orderId", getIntent().getIntExtra("orderId", 0));
        intent.putExtra("type",DETAIL_DELIVER_TYPE);
        startActivityForResult(intent,DETAIL_DELIVER_TYPE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==DETAIL_DELIVER_TYPE&&resultCode==RESULT_OK){
            finish();
        }
    }
}
